<?php

class ExpressController extends CoreController
{

    protected $authExcept = ['callback'];

    /**
     * 物流信息订阅回调接口
     */
    public function callbackAction()
    {
        $requestData = $this->postData;

        $expressLib = new \app\service\express();

        // 信息记录日志
        // \think\Log::write('expresscallback:'. json_encode($requestData));
        if(empty($requestData['RequestData'])) {
            ret(30001, '物流信息为空');
        }
        Log::out($requestData['RequestData'], 'express');

        $data        = json_decode(html_entity_decode($requestData['RequestData']), true);
        $expressData = $data['Data'];

        foreach ($expressData as $key => $express) {
            // 查找包裹
            $orderExpress = orderexpressModel::with('order')->where('express_code', $express['ShipperCode'])
                ->where('express_no', $express['LogisticCode'])
                ->get();

            if (!$orderExpress) {
                // 包裹不存在,记录日志信息，然后继续下一个
                Log::out('orderExpressNotFound:' . json_encode($express));
                continue;
            }

            if (!$express['Success']) {
                // 失败了
                if (isset($express['Reason']) && ($express['Reason'] == '三天无轨迹' || $express['Reason'] == '七天无轨迹')) {
                    // 需要重新订阅
                    $expressLib->subscribe([
                        'express_code' => $express['ShipperCode'],
                        'express_no'   => $express['LogisticCode']
                    ], $orderExpress, $orderExpress->order);
                }

                Log::out('orderExpressReason:' . json_encode($express));
                continue;
            }

            foreach ($orderExpress as $oes) {
                $expressLib->checkAndAddTraces($oes, $express);
            }
        }

        echo $expressLib->setPushResult(true);
    }
}
